package com.example.bitintershipbbs.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.bitintershipbbs.DTO.Msg;
import com.example.bitintershipbbs.mapper.PostMapper;
import com.example.bitintershipbbs.mapper.UserMapper;
import com.example.bitintershipbbs.model.Post;
import com.example.bitintershipbbs.model.User;
import com.example.bitintershipbbs.provider.ImageBedProvider;
import com.example.bitintershipbbs.provider.ImageLocalProvider;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@CrossOrigin
@Controller
public class PublishController {
    @Autowired
    private PostMapper postMapper;

    @Autowired
    private UserMapper userMaper;
    @Autowired
    private ImageLocalProvider imageLocalProvider;

    @PostMapping("/publish")
    public ResponseEntity<Object> publishPost(@Param("title") String title,
                                              @Param("description") String description,
                                              @Param("location") String location,
                                              @Param("position") String position,
                                              @Param("sallary") String sallary,
                                              @Param("type") String type,
                                              HttpServletRequest request,
                                              HttpServletResponse response){
        Msg msg = new Msg();
        Post post = new Post();

        User user = (User) request.getSession().getAttribute("user");
        if (user != null) {
            post.setCreatorid(user.getId());
            post.setTitle(title);
            post.setType(type);
            post.setDescription(description);
            post.setLocation(location);
            post.setSallary(sallary);
            post.setPosition(position);
            post.setGmt_create(System.currentTimeMillis());
            post.setGmt_modified(post.getGmt_create());
            postMapper.createPost(post);
            msg.setCode(200);
            msg.setMessage("发布成功");
            return ResponseEntity.status(200).body(msg);
        }
        else {
            Cookie[] cookies = request.getCookies();
            if (cookies != null && cookies.length > 0) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("token")) {
                        String token = cookie.getValue();
                        user = userMaper.findByToken(token);
                        if (user != null) {
                            post.setCreatorid(user.getId());
                            post.setTitle(title);
                            post.setType(type);
                            post.setDescription(description);
                            post.setLocation(location);
                            post.setSallary(sallary);
                            post.setPosition(position);
                            post.setGmt_create(System.currentTimeMillis());
                            post.setGmt_modified(post.getGmt_create());

                            postMapper.createPost(post);

                            msg.setCode(200);
                            msg.setMessage("发布成功");

                            return ResponseEntity.status(200).body(msg);
                        }
                        else {
                            msg.setCode(400);
                            msg.setMessage("发布失败，用户没有登录");
                            return ResponseEntity.status(400).body(msg);
                        }
                    }
                }
            }
        }

        msg.setCode(400);
        msg.setMessage("发布失败，用户没有登录");
        return ResponseEntity.status(400).body(msg);
    }

    @RequestMapping("/imformation/add")
    public ResponseEntity<Object> addAvatar(@RequestParam("file") MultipartFile multipartFile,
                      HttpServletRequest request,
                      HttpServletResponse response) throws IOException {
        Msg msg = new Msg();
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            Cookie[] cookies = request.getCookies();
            if (cookies != null && cookies.length > 0) {
                for (Cookie cookie: cookies) {
                    if (cookie.getName().equals("token")) {
                        String token = cookie.getValue();
                        user = userMaper.findByToken(token);
                        if(user==null){
                            msg.setCode(400);
                            msg.setMessage("用户未登录");
                            return ResponseEntity.status(400).body(msg);
                        }
                    }
                }
            }
        }
        String avatar_url = imageLocalProvider.upload(multipartFile);
        user.setAvatar_url(avatar_url);
        userMaper.addAvatar(user);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("avatar_url", avatar_url);
        return ResponseEntity.status(200).body(jsonObject);
//        if(user.getAvatar_url()==null){
//            String avatar_path = imageBedProvider.upload("demo", multipartFile);
//            String avatar_url = imageBedProvider.getPRE() + avatar_path;
//            user.setAvatar_url(avatar_url);
//            userMaper.addAvatar(user);
//            msg.setCode(200);
//            msg.setMessage("添加成功");
//            return ResponseEntity.status(200).body(msg);
//        }
//        else {
//            String avatar_url = user.getAvatar_url();
//            avatar_url.split("/");
//            String avatar_path = avatar_url.split("/")[avatar_url.split("/").length -1];
//            avatar_path = "demo/" + avatar_path;
//            imageBedProvider.delete(avatar_path);
//            avatar_path = imageBedProvider.upload("demo", multipartFile);
//            avatar_url = imageBedProvider.getPRE() + avatar_path;
//            user.setAvatar_url(avatar_url);
//            userMaper.addAvatar(user);
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("avatar_url", avatar_url);
//            return ResponseEntity.status(200).body(jsonObject);
//        }
    }

    @PostMapping("/getposts")
    public ResponseEntity<Object> getUserPosts(HttpServletRequest request,
                                               HttpServletResponse response){
        Msg msg = new Msg();
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            Cookie[] cookies = request.getCookies();
            if (cookies != null && cookies.length > 0) {
                for (Cookie cookie: cookies) {
                    if (cookie.getName().equals("token")) {
                        String token = cookie.getValue();
                        user = userMaper.findByToken(token);
                        if(user==null){
                            msg.setCode(400);
                            msg.setMessage("用户未登录");
                            return ResponseEntity.status(400).body(msg);
                        }
                    }
                }
            }
        }
        List<Post> postList = postMapper.getListById(user.getId());
        JSONObject resultObject = new JSONObject();
        resultObject.put("code",200);
        resultObject.put("content", postList);
        return ResponseEntity.status(200).body(resultObject);
    }

}
